package com.example.idachuappone.index.item;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.R;
import com.example.idachuappone.cook.entity.WorkDay;
import com.example.idachuappone.index.dialog.DialogServiceDateHours;
import com.example.idachuappone.index.dialog.DialogServiceDateHours.CallBack;
import com.example.idachuappone.index.entity.HotServiceItemDetail;
import com.example.idachuappone.person.item.LoginActivity;
import com.example.idachuappone.promptly.entity.Addresses;
import com.example.idachuappone.promptly.item.CookAddressListActivity;
import com.example.idachuappone.utils.BitmapUtilHelper;
import com.example.idachuappone.utils.Constant;
import com.example.idachuappone.utils.CusProSmallBgDialog;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class HotPrompActivity extends BaseActivity implements OnClickListener {
	private int addressRequestCode;
	private Addresses addresses;
	private Button btn_back;
	private Button btn_submit;
	private BitmapUtils bu;
	private CusProSmallBgDialog cusProDialog;
	private List<WorkDay> dates;
	private String detailTimeFormat;
	private Dialog dialogTime;
	private EditText et_desc;
	private HotServiceItemDetail hotServiceItemDetail;
	private ImageView img;
	private boolean isNoAddress;
	private LinearLayout ll_address;
	private LinearLayout ll_address_gone;
	private LinearLayout ll_address_visible;
	private LinearLayout ll_time;
	private LinearLayout ll_time_gone;
	private LinearLayout ll_time_visible;
	private int loginRequest;
	private TextView tv_day;
	private TextView tv_desc;
	private TextView tv_desc_top;
	private TextView tv_hour_min;
	private TextView tv_name;
	private TextView tv_price;
	private TextView tv_user_address;
	private TextView tv_user_name;
	private TextView tv_user_phone;
	private TextView tv_year_mon_day;

	public HotPrompActivity() {
		this.addressRequestCode = 15;
		this.loginRequest = 255;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hot_promp);
		this.cusProDialog = new CusProSmallBgDialog(this);
		this.bu = BitmapUtilHelper.createBitmapUtil(this);
		this.hotServiceItemDetail = (HotServiceItemDetail) getIntent().getSerializableExtra("hotServiceItemDetail");
		this.dates = (List) getIntent().getSerializableExtra("dates");
		initView();
		initDateTime(this);
		setDataView();
	}

	private void setDataView() {
		this.tv_name.setText(this.hotServiceItemDetail.getName());
		this.tv_desc_top.setText(this.hotServiceItemDetail.getPeople_num());
		this.tv_price.setText(this.hotServiceItemDetail.getPrice());
		this.bu.display(this.img, this.hotServiceItemDetail.getFirst_img());
	}

	private void initView() {
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.img = (ImageView) findViewById(R.id.img);
		this.tv_name = (TextView) findViewById(R.id.tv_name);
		this.tv_desc_top = (TextView) findViewById(R.id.tv_desc_top);
		this.tv_price = (TextView) findViewById(R.id.tv_price);
		this.btn_submit = (Button) findViewById(R.id.btn_submit);
		this.btn_submit.setOnClickListener(this);
		this.ll_time = (LinearLayout) findViewById(R.id.ll_time);
		this.ll_time.setOnClickListener(this);
		this.ll_time_gone = (LinearLayout) findViewById(R.id.ll_time_gone);
		this.ll_time_visible = (LinearLayout) findViewById(R.id.ll_time_visible);
		this.tv_day = (TextView) findViewById(R.id.tv_day);
		this.tv_year_mon_day = (TextView) findViewById(R.id.tv_year_mon_day);
		this.tv_hour_min = (TextView) findViewById(R.id.tv_hour_min);
		this.ll_address = (LinearLayout) findViewById(R.id.ll_address);
		this.ll_address.setOnClickListener(this);
		this.ll_address_gone = (LinearLayout) findViewById(R.id.ll_address_gone);
		this.ll_address_visible = (LinearLayout) findViewById(R.id.ll_address_visible);
		this.tv_user_name = (TextView) findViewById(R.id.tv_user_name);
		this.tv_user_phone = (TextView) findViewById(R.id.tv_user_phone);
		this.tv_user_address = (TextView) findViewById(R.id.tv_user_address);
		initAddress();
		this.tv_desc = (TextView) findViewById(R.id.tv_desc);
		this.et_desc = (EditText) findViewById(R.id.et_desc);
		this.et_desc.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					HotPrompActivity.this.tv_desc.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				}
			}
		});
		this.et_desc.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (HotPrompActivity.this.et_desc.getText().toString().length() >= 100) {
					MainToast.show(HotPrompActivity.this, "\u5907\u6ce8\u6700\u591a\u53ef\u8f93\u5165100\u5b57", 0);
				}
			}
		});
	}

	private void initAddress() {
		PrefUtil pp = PrefUtil.getInstance(this);
		if (pp.getXiaoQu() == null || pp.getXiaoQu().length() <= 0) {
			this.isNoAddress = true;
			this.ll_address_gone.setVisibility(0);
			this.ll_address_visible.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
			return;
		}
		this.isNoAddress = false;
		this.ll_address_gone.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
		this.ll_address_visible.setVisibility(0);
		this.addresses = new Addresses(pp.getUserAddressId(), "", pp.getName(), pp.getPhone(), pp.getArea(),
				pp.getXiaoQu(), pp.getDoor(), "", "");
		setAddress(this.addresses);
	}

	private void setAddress(Addresses addresses) {
		this.tv_user_name.setText(addresses.getName());
		this.tv_user_phone.setText(addresses.getPhone());
		this.tv_user_address.setText(addresses.getCommunity() + addresses.getDoor_number());
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (this.isNoAddress) {
			initAddress();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			finish();
		case R.id.ll_address /* 2131165259 */:
			if (PrefUtil.getInstance(this).getUID() == null) {
				MainToast.show(this, "\u60a8\u8fd8\u6ca1\u6709\u767b\u5f55\uff0c\u8bf7\u5148\u767b\u5f55", 0);
				startActivityForResult(new Intent(this, LoginActivity.class), this.loginRequest);
				return;
			}
			Intent intent = new Intent(this, CookAddressListActivity.class);
			if (this.addresses != null) {
				intent.putExtra("userAddressId", this.addresses.getId());
			}
			startActivityForResult(intent, this.addressRequestCode);
		case R.id.ll_time /* 2131165265 */:
			this.dialogTime.show();
		case R.id.btn_submit /* 2131165282 */:
			if (PrefUtil.getInstance(this).getUID() == null) {
				MainToast.show(this, "\u60a8\u8fd8\u6ca1\u6709\u767b\u5f55\uff0c\u8bf7\u5148\u767b\u5f55", 0);
				startActivityForResult(new Intent(this, LoginActivity.class), this.loginRequest);
			} else if (this.addresses == null) {
				MainToast.show(this, "\u8bf7\u60a8\u5b8c\u5584\u5730\u5740\u4fe1\u606f", 0);
			} else if (this.detailTimeFormat == null || this.detailTimeFormat.trim().length() <= 0) {
				MainToast.show(this, "\u8bf7\u60a8\u9009\u62e9\u65f6\u95f4", 0);
			} else {
				this.btn_submit.setEnabled(false);
				Map<String, String> map = new HashMap();
				map.put("date", this.detailTimeFormat);
				map.put("package_type", "3");
				map.put("package",
						new StringBuilder(String.valueOf(this.hotServiceItemDetail.getId())).append("-")
								.append(this.hotServiceItemDetail.getPrice()).toString());
				map.put("area", this.addresses.getArea());
				map.put("community", this.addresses.getCommunity());
				map.put("door_number", this.addresses.getDoor_number());
				map.put("name", this.addresses.getName());
				map.put("phone", this.addresses.getPhone());
				map.put("ver", "2");
				map.put("memo", this.et_desc.getText().toString());
				map.put("app", "2");
				NetUtil.post(this, Constant.PROMPTLY, map, new RequestCallBack<String>() {
					@Override
					public void onStart() {
						super.onStart();
						HotPrompActivity.this.cusProDialog.setMsg("\u63d0\u4ea4\u8ba2\u5355\u4e2d...");
						HotPrompActivity.this.cusProDialog.show();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						HotPrompActivity.this.cusProDialog.dismiss();
						try {
							JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(responseInfo.result));
							if (jsonObject.getInt("code") == 10000) {
								HotPrompActivity.this.startActivity(new Intent(HotPrompActivity.this,
										HotPrompOkActivity.class));
								return;
							}
							MainToast.show(HotPrompActivity.this, jsonObject.getString("error"), 0);
							HotPrompActivity.this.btn_submit.setEnabled(true);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						HotPrompActivity.this.btn_submit.setEnabled(true);
						HotPrompActivity.this.cusProDialog.dismiss();
						MainToast.show(HotPrompActivity.this,
								HotPrompActivity.this.getResources().getString(R.string.netFail), 0);
					}
				});
			}
		default:
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == this.addressRequestCode && resultCode == -1) {
			this.addresses = (Addresses) data.getExtras().getSerializable("address");
			setAddress(this.addresses);
		}
		if (requestCode == this.loginRequest && resultCode == -1) {
			initAddress();
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == 0) {
			View v = getCurrentFocus();
			if (isShouldHideInput(v, ev)) {
				hideSoftInput(v.getWindowToken());
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	private boolean isShouldHideInput(View v, MotionEvent event) {
		if (v == null || !(v instanceof EditText)) {
			return false;
		}
		int[] l = new int[2];
		v.getLocationInWindow(l);
		int left = l[0];
		int top = l[1];
		return event.getX() <= (left) || event.getX() >= (left + v.getWidth()) || event.getY() <= (top)
				|| event.getY() >= (top + v.getHeight());
	}

	private void hideSoftInput(IBinder token) {
		if (token != null) {
			((InputMethodManager) getSystemService("input_method")).hideSoftInputFromWindow(token,
					BitmapCacheManagementTask.MESSAGE_FLUSH);
			if (this.et_desc.getText().toString().trim().length() == 0) {
				this.tv_desc.setVisibility(0);
			}
			this.et_desc.clearFocus();
		}
	}

	private void initDateTime(Context context) {
		this.dialogTime = new DialogServiceDateHours(context).showDateHours(this, new CallBack() {
			@Override
			public void btnOk(WorkDay workDay, int hourindex, String min) {
				HotPrompActivity.this.detailTimeFormat = workDay.getDate() + " " + workDay.getHh()[hourindex] + ":"
						+ min;
				HotPrompActivity.this.ll_time_gone.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				HotPrompActivity.this.ll_time_visible.setVisibility(0);
				HotPrompActivity.this.tv_day.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				HotPrompActivity.this.tv_year_mon_day.setText(workDay.getDate());
				HotPrompActivity.this.tv_hour_min.setText(new StringBuilder(String.valueOf(workDay.getHh()[hourindex]))
						.append(":").append(min).toString());
				HotPrompActivity.this.dialogTime.dismiss();
			}
		}, this.dates);
	}
}
